package com.CatTalkApi.Servlet;

import com.CatTalkApi.DAO.DataBaseContext;
import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import javax.xml.crypto.Data;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/AddUsr")
public class AddUsrInfoServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("Content-Type", "application/json;");

        System.out.println("AddUsr Method: " + req.getMethod());
        //配置跨域
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, OPTIONS, PATCH");
        resp.setHeader("Access-Control-Allow-Headers", "authorization, content-type,token,identify");
        resp.setHeader("Access-Control-Expose-Headers", "X-forwared-port, X-forwarded-host");
        resp.setHeader("Vary", "Origin,Access-Control-Request-Method,Access-Control-Request-Headers");
        super.service(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        JSONObject readJson = JsonReader.receivePost(req);
        String usrID = (String) readJson.get("usrID");
        String usrPwd = (String) readJson.get("usrPwd");
        String usrDescription = (String) readJson.get("usrDescription");
        String usrGender = (String) readJson.get("usrGender");
        //添加数据进入数据库中
        boolean rest = true;
        try {
            var sqlST = String.format("INSERT INTO `usrinfo`(`Name`,`Gender`,`Description`,`UsrPwd`) VALUES('%s','%s','%s','%s')", usrID, usrGender, usrDescription, usrPwd);
            rest = !DataBaseContext.getInstance().GetStmt().execute(sqlST);
            System.out.println("执行的查询语句" + sqlST);
            DataBaseContext.getInstance().Close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            rest = false;
        }

        if (rest == false) {
            resp.setStatus(423); //已经存在了一个用户，创建失败了
        } else {
            resp.setStatus(200);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
